import { connectToDatabase } from '../data/db.js'
import {
  COLLECTION_QUESTION_COMPONENTS_LIST,
  COLLECTION_QUESTION_ANSWER_LIST
} from '../constant/dbConfig.js'
import { Result } from '../utils/result.js'

const db = await connectToDatabase()
// 连接到component表
const componentCollection = await db.collection(
  COLLECTION_QUESTION_COMPONENTS_LIST
)
// 问卷答案表
const answerCollection = await db.collection(COLLECTION_QUESTION_ANSWER_LIST)

export default [
  // 根据问卷id获取答卷列表
  {
    url: '/api/question/getAnswerList',
    method: 'get',
    response: async ctx => {
      const { questionId, pageNum = 1, pageSize = 10 } = ctx.query

      if (!questionId) {
        return Result.error('Question ID is required')
      }

      try {
        const query = { questionId: questionId }
        const skip = (pageNum - 1) * pageSize // 计算跳过的文档数量
        const limit = parseInt(pageSize, 10) // 每页文档数量

        // 从答案表中分页获取数据
        const total = await answerCollection.countDocuments(query) // 获取总记录数
        const answers = await answerCollection
          .find(query)
          .skip(skip)
          .limit(limit)
          .toArray() // 分页查询

        const rows = answers.map(answer => {
          const { _id, questionId, answers } = answer
          return {
            _id,
            questionId,
            ...answers
          }
        })

        return Result.success({
          total, // 总记录数
          pageNum: parseInt(pageNum, 10), // 当前页码
          pageSize: limit, // 每页数量
          rows // 当前页数据
        })
      } catch (error) {
        return Result.error('Failed to fetch answer list').setMsg(
          JSON.stringify(error)
        )
      }
    }
  },
  // 获取某个问卷中某个组件的统计结果
  {
    url: '/api/question/stat',
    method: 'get',
    response: async ctx => {
      try {
        const { questionId, componentId, name } = ctx.query

        if (!questionId || !componentId) {
          return Result.error('Question ID and Component ID are required')
        }

        // 1. 根据问卷ID获取组件列表
        const query = { questionId: questionId }
        const componentsList = await componentCollection.find(query).toArray()

        // 2. 获取某个组件信息
        const componentInfo = componentsList.find(
          item => item._id.toString() === componentId
        )
        if (!componentInfo) {
          return Result.error().setMsg('组件ID不存在')
        }

        // 3. 获取答卷列表
        const answerList = await answerCollection.find(query).toArray()

        // 4. 判断组件类型，统计答案出现的次数
        const stat = {}
        for (const answer of answerList) {
          // 这个组件对应的答案
          const componentAnswer = answer.answers[name]
          if (componentInfo.type === 'QuestionCheckbox') {
            // 多选题：将逗号分隔的字符串解析为数组
            const options = componentAnswer.split(',')
            options.forEach(option => {
              stat[option.trim()] = (stat[option.trim()] || 0) + 1
            })
          } else if (componentInfo.type === 'QuestionRadio') {
            // 单选题
            stat[componentAnswer] = (stat[componentAnswer] || 0) + 1
          }
        }

        // 格式化统计结果
        const result = Object.entries(stat).map(([value, count]) => ({
          value,
          count
        }))

        // 5. 返回结果信息
        return Result.success(result)
      } catch (error) {
        return Result.error(
          'Failed to fetch answer list',
          JSON.stringify(error)
        )
      }
    }
  },
  // 保存问卷答案
  {
    url: '/h5/submitAnswer',
    method: 'post',
    response: async ctx => {
      const { questionId, answers } = ctx.request.body

      if (!questionId) return Result.error('问卷ID不能为空')
      try {
        const res = await answerCollection.insertOne({
          questionId: questionId,
          answers: answers
        })
        return Result.success(res)
      } catch (error) {
        return Result.error(error)
      }
    }
  }
]
